﻿using System;
using System.Collections.Generic;
using System.Configuration;
using System.Linq;
using System.IO;
using System.Web;
using System.Web.Mvc;
using Ext.Net;
using Ext.Net.MVC;
using WebEntities;
using WebEntities.Models.ProductInfo;
using com.subb.ProductInfo;
using WebAdmin.CommonCls;

namespace WebAdmin.Controllers
{
    [Authorize]
    public class ProductImgController : Controller
    {
        private const string PRODUCTIMG_PATH = "ProductImgs/";

        public ActionResult GetAllProductImg(int prodId)
        {
            PP_ProductImgDAL pidal = new PP_ProductImgDAL();
            List<PP_ProductImg> ppimgList = pidal.GetAllProductImg(prodId);
            List<ProductImg> pimgList = new List<ProductImg>();
            foreach (var ppimg in ppimgList)
            {
                ProductImg pimg = ProductImg.AsProductImg(ppimg);
                pimgList.Add(pimg);
            }
            return this.Store(pimgList);
        }

        public ActionResult NewProductImgWindow(int prodId)
        {
            Window wnd = new Window()
            {
                ID = "Window1",
                Title = "上传产品图片",
                Width = 600,
                Height = 450,
                Modal = true,
                Maximizable = true,
                Icon = Ext.Net.Icon.Image,
                Loader = new ComponentLoader
                {
                    Url = Url.Action("UploadProductImg"),
                    Mode = LoadMode.Frame,
                    LoadMask =
                    {
                        ShowMask = true,
                        Msg = "加载中，请稍候..."
                    }
                }
            };
            wnd.Loader.Params.Add(new Parameter("prodId", prodId.ToString()));
            wnd.Render();
            return this.Direct();
        }

        public ActionResult UploadProductImg(int prodId)
        {
            ViewData["ProductID"] = prodId;
            return View();
        }

        [HttpPost]
        public ActionResult UploadProductImg(ProductImg prodImg)
        {
            FormPanelResult response = new FormPanelResult();
            response.IsUpload = true;
            try
            {
                string creator = Request.IsAuthenticated ? HttpContext.User.Identity.Name : "Anonymous";
                prodImg.Creator = creator;
                PP_ProductImgDAL pidal = new PP_ProductImgDAL();
                int id = pidal.CreateProductImg(prodImg);
                //上传文件
                if (Request.Files.Count > 0)
                {
                    HttpFileCollectionBase fb = Request.Files;
                    HttpPostedFileBase fpfb1 = fb.Get("ProductImage");
                    string savePath = string.Empty;
                    //上传产品封面图
                    if (fpfb1 != null && fpfb1.ContentLength > 0)
                    {
                        string uploadVFolder = ConfigurationManager.AppSettings["UploadVFolder"];
                        if (!string.IsNullOrWhiteSpace(uploadVFolder))
                        {
                            savePath = Server.MapPath(uploadVFolder + PRODUCTIMG_PATH);
                            if (!Directory.Exists(savePath))
                            {
                                Directory.CreateDirectory(savePath);
                            }
                            string extName = Path.GetExtension(fpfb1.FileName);
                            savePath += "pimg" + prodImg.ProductID + "_" + id + extName;
                            fpfb1.SaveAs(savePath);
                            ProductImgUtils.ResizeProductImg(savePath);
                            //更新路径
                            string webpath = uploadVFolder + PRODUCTIMG_PATH + "pimg" + prodImg.ProductID + "_" + id + extName;
                            ProductImg updPimg = ProductImg.AsProductImg(pidal.GetProductImg(id));
                            updPimg.ImgUrl = webpath;
                            pidal.UpdateProductImg(id, updPimg);
                        }
                    }
                }
                response.Success = true;
                response.ExtraParams.Add(new Parameter("Msg", "图片上传成功！"));
                return response;
            }
            catch (Exception ex)
            {
                response.Success = false;
                response.ExtraParams.Add(new Parameter("Msg", ex.InnerException != null ? ex.InnerException.Message : ex.Message));
                return response;
            }
        }

        [HttpPost]
        public ActionResult DeleteProductImg([ModelBinder(typeof(JsonModelBinder))]Dictionary<string, string>[] images)
        {
            try
            {
                PP_ProductImgDAL pidal = new PP_ProductImgDAL();
                foreach (var pimg in images)
                {
                    int id;
                    if (int.TryParse(pimg["ID"], out id))
                    {
                        string webpath = pimg["ImgUrl"];
                        string realpath = Server.MapPath(webpath);                        
                        System.IO.File.Delete(realpath);
                        pidal.RemoveProductImg(id);
                    }
                }
                return this.Direct(new { Success = true, Msg = "图片删除成功！" });
            }
            catch (Exception ex)
            {
                return this.Direct(new { Success = false, Msg = ex.InnerException != null ? ex.InnerException.Message : ex.Message });
            }
        }
    }
}
